package eu.tsp.isensors.test.communication;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import java.io.IOException;
import java.lang.reflect.Method;


public abstract class  RestServlet extends HttpServlet {

   private static final long serialVersionUID = 1L;

   //private static Logger logger = Logger.getLogger(RestServlet.class.getName());

   protected RestServlet() {
       super();
   }

   protected abstract ResourceIdentifier[] resourceIdentifiers();

   /** try calling doGet, doPost, or whatever, on each ResourceIdentifier, until one succeeds. 
Uses reflection to reduce bloat.
*/

   private void doMethod(String methodName, HttpServletRequest request,
           HttpServletResponse response) throws ServletException, IOException {
       boolean did = false;
       try {
           // The method must be like e.g.
           // boolean doGet(HttpServletRequest request, HttpServletResponse response)
           Method method = ResourceIdentifier.class.getMethod(methodName, new Class[]{HttpServletRequest.class, HttpServletResponse.class});
           Object [] params = new Object[]{request, response};
           for (ResourceIdentifier rid : resourceIdentifiers()) {
               if (did = (Boolean)method.invoke(rid, params)) {
                   break;
               }
           }
           if (!did) {
               response.sendError(HttpServletResponse.SC_NOT_FOUND);
           }
       } catch (Exception e) {
           //logger.log(Level.SEVERE, "Exception in doPost", e);
           throw new ServletException(e);
       }

   }

   @Override
   protected void doPost(HttpServletRequest request,
           HttpServletResponse response) throws ServletException, IOException {
       doMethod ("doPost", request, response);

   }

   @Override
   protected void doGet(HttpServletRequest request,
           HttpServletResponse response) throws ServletException, IOException {
       doMethod ("doGet", request, response);
   }

   @Override
   protected void doPut(HttpServletRequest request,
           HttpServletResponse response) throws ServletException, IOException {
       doMethod ("doPut", request, response);
   }

   @Override
   protected void doDelete(HttpServletRequest request,
           HttpServletResponse response) throws ServletException, IOException {
       doMethod ("doDelete", request, response);
   }
}
